﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace SangsTools
{
    public class PosFollowerMgr : SingletonMono<PosFollowerMgr>
    {
        public Dictionary<string, IPosFollower> dicFollower;

        protected override void OnCreate()
        {
            base.OnCreate();
            dicFollower = new Dictionary<string, IPosFollower>();

            //没10秒调用一次自动去空
            InvokeRepeating("RemoveEmptyData", 10, 10);
        }

        /// <summary>
        /// 注册一个最基础的跟随器
        /// </summary>
        /// <param name="follow"></param>
        /// <param name="target"></param>
        /// <returns></returns>
        public static string AddNormalFollower(Transform follow, Transform target)
        {
            return AddFollower(new TransformPosFollower(follow, target));
        }

        /// <summary>
        /// 注册跟随信息
        /// </summary>
        /// <param name="followerData"></param>
        /// <returns></returns>
        public static string AddFollower(IPosFollower followerData)
        {
            if (followerData == null || followerData.CheckIsEmpty()) return null;

            string key = System.Guid.NewGuid().ToString();
            Ins.dicFollower.Add(key, followerData);
            return key;
        }
        /// <summary>
        /// 注销跟随信息
        /// </summary>
        /// <param name="key"></param>
        public static void RemoveFollowerData(string key)
        {
            if (string.IsNullOrEmpty(key)) return;
            if (Ins.dicFollower.ContainsKey(key))
                Ins.dicFollower.Remove(key);
        }

        private void LateUpdate()
        {
            foreach (var item in dicFollower.Values)
            {
                item?.Follow();
            }
        }

        /// <summary>
        /// 去空方法，create后定时触发
        /// </summary>
        private void RemoveEmptyData()
        {
            List<string> listTmp = new List<string>();
            listTmp.AddRange(dicFollower.Keys);
            for (int i = 0; i < listTmp.Count; i++)
            {
                IPosFollower follower;
                if (dicFollower.TryGetValue(listTmp[i], out follower))
                    if (follower == null || follower.CheckIsEmpty())
                        dicFollower.Remove(listTmp[i]);
            }
        }
    }
}